<template>
  <div class="index_container">
    <qr-item style="z-index: -99999;position:fixed;top: -10000px" ref="qrcode"
             :qrTextSize="80"
             :qrSize="600"
             :qr2Text='qrCode2Text' :qrUrl="qrCode2Url" ></qr-item>
    <div class="staff_title">全部员工</div>
    <div class="staff_top">
      <el-form :inline="true" :model="staffForm">
        <el-form-item label="员工名称" prop="username">
          <el-input
              class=""
              v-model="staffForm.username"
              placeholder="请输入用户名称"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-button @click="addStaff" class="staff_btn">添加用户</el-button>
    </div>
    <div>
      <myTabel
          stripe
          v-if="showMyTable"
          :columnData="columnData"
          :data="filterStaffList"
      >
        <el-table-column label="操作" align="left" width="190px">
          <template slot-scope="scope">
            <el-button type="text" @click="editUser(scope.row)">
              修改
            </el-button
            >
            <el-button type="text el-button--del" @click="del(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </myTabel>
      <el-dialog :visible="isVisible" :title="title" width="660px"
      @close="cancal"
      >
        <div class="dialog_content">
          <el-form
              :inline="true"
              label-position="right"
              :model="addStaffForm"
              label-width="80px"
          >
            <el-form-item label="员工名称" prop="username">
              <el-input v-model="addStaffForm.username"></el-input>
            </el-form-item>
            <el-form-item label="联系方式" prop="contact">
              <el-input v-model="addStaffForm.contact"></el-input>
            </el-form-item>
            <el-form-item label="员工工价" prop="price_table">






<!--              上传文件-->
              <el-upload
                  class="upload-demo"
                  action="/admin/api/uploadExcel"
                  name="excel"
                  :on-preview="handlePreview"
                  :limit="1"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :file-list="fileList"
                  :on-success="handleSuccess"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传一个表格文件，若需这次修改请删除重新上传</div>
              </el-upload>



            </el-form-item>
            <el-form-item label="工号" prop="job_number">
              <el-input v-model="addStaffForm.job_number"></el-input>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="addStaffForm.remark"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="cancal">取 消</el-button>
          <el-button type="primary" @click="submitAdd">确 定</el-button>
        </span>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import {
  getUser,
  addUser,
  delUser,
  updateUser,
} from "@/request/api/defaultApi/defaultApi";
import myTabel from "@/components/myTable/index.vue";
import QrItem from './qrcode.vue'

import axios from "axios";
import VueQrcode from 'vue-qrcode'

export default {
  components: {myTabel,VueQrcode,QrItem},
  computed: {
    filterStaffList() { //
      return this.tableData.filter((item) => {
        return item.username.includes(this.staffForm.username);
      });
    },
  },
  data() {
    const _this = this;
    return {
      qrCode2Text: '',
      qrCode2Url: '',
      fileList: [],
      isVisible: false,
      showMyTable: true,
      staffForm: {
        username: "",
      },
      addStaffForm: {
        username: "",
        contact: "",
        price_table: "",
        job_number: "",
        remark: "",
      },
      columnData: [
        {
          prop: "username",
          label: "用户名称",
          "min-width": "120",
        },
        {
          prop: "contact",
          label: "联系方式",
          "min-width": "120",
        },
        {
          prop: "job_number",
          label: "工号",
          "min-width": "80",
        },
        {
          prop: "remark",
          label: "备注",
          "min-width": "100",
        },
        {
          prop: "qrCode",
          label: "二维码",
          "min-width": "120",
          render(h, row) {
            return h(
                "el-button",
                {
                  on: {
                    click: () => {
                      _this.generateAndDownloadQRCode(row);
                    },
                  },
                },
                // [row.id]
                "下载"
            );
          },
        },
        {
          prop: "price_table",
          label: "工价表",
          "min-width": "160",
          render(h, row) {
            return h(
                "el-button",
                {
                  on: {
                    click: () => {
                      _this.download(row);
                    },
                  },
                },
                // [row.id]
                "下载"
            );
          },
        },
      ],
      title: "",
      tableData: [],
    };
  },
  created() {
    this.getUserList();
  },

  methods: {
    onDataUrlChange(dataUrl) {
      console.log(dataUrl);
    },

    // 下载二维码
    generateAndDownloadQRCode(row) {
      this.qrCode2Text = row.username
      this.qrCode2Url = window.location.origin + '/dist/client/#/pages/produc_list/index?id=' + row.id

      this.$nextTick(() => {
        this.$refs.qrcode.savePic()
      })

    },

    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handleSuccess(response, file, fileList) {
      console.log(response, file, fileList);
      this.$message({
        message: '上传成功',
        type: 'success'
      });
      this.fileList = fileList;
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    download(data) {

      axios.get( data.price_table, { responseType: 'blob' })
          .then(response => {
            const fileBlob = new Blob([response.data], { type: response.headers['content-type'] });
            const fileUrl = URL.createObjectURL(fileBlob);

            // 创建一个隐藏的链接元素
            const link = document.createElement('a');
            link.download = data.username + '工价表';
            link.href = fileUrl;

            // 添加链接元素到页面
            document.body.appendChild(link);

            // 触发点击事件进行下载
            link.click();

            // 清理链接元素
            document.body.removeChild(link);
          })
          .catch(error => console.error('文件下载失败:', error));



    },




    // handleSearch() {
    //   if (this.staffForm.username) {
    //     this.tableData = this.tableData.filter((item) => {
    //       return item.username.includes(this.staffForm.username);
    //     });
    //   } else {
    //     this.getUserList();
    //   }
    // },
    // 获取用户列表
    getUserList() {
      getUser().then((res) => {
        this.tableData = res.data;
      });
    },
    // 打开弹框
    addStaff() {
      this.title = "添加用户";
      this.isVisible = true;
    },
    // 添加用户
    submitAdd() {
      const data = {
        params: this.addStaffForm,
      };
      if (data.params.id) {
        updateUser(data).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "修改成功",
            });
            this.cancal();
            this.getUserList();
          }
        });
      } else {
        addUser(data).then((res) => {
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "添加成功",
            });
            this.cancal();
            this.getUserList();
          }
          console.log("🚀 ~ file: Index.vue:118 ~ addUser ~ res:", res);
        });
      }
      console.log(this.addStaffForm);
    },
    // 删除用户
    del(val) {
      const data = {
        id: val.id,
      };
      console.log("🚀 ~ file: Index.vue:141 ~ del ~ val:", val);
      delUser(data).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: "success",
            message: "删除成功",
          });
          this.getUserList();
        }
        console.log(res, "asdasdas");
      });
    },
    // 修改用户
    editUser(val) {
      this.addStaffForm = val;
      this.title = "编辑用户";
      this.isVisible = true;
      console.log("🚀 ~ file: Index.vue:176 ~ editUser ~ val:", val);
    },
    // 关闭弹框
    cancal() {
      this.isVisible = false;
      this.addStaffForm = {
        username: "",
        contact: "",
        price_table: "",
        job_number: "",
        remark: "",
      };
    },
  },
  mounted() {
  },

  //监听上传文件
  watch: {
    fileList: {
      handler: function (newVal, oldVal) {
        console.log(newVal)
        if (newVal.length > 0) {
          this.addStaffForm.price_table = newVal[0].response.data.url
        }
      },
      deep: true,
    },
  },


};
</script>

<style lang="scss">
.staff_title {
  font-size: 24px;
  font-weight: 500;
}

.staff_top {
  display: flex;
  justify-content: space-between;
  margin: 10px 0;

  .staff_btn {
    height: 32px;
    line-height: 10px;
  }
}

.dialog_content {
  width: 400px;
  margin: 0 auto;
}
</style>
